package com.example.admin.datasupport.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.annotation.RequiresApi;
import android.telecom.Call;

import com.example.admin.datasupport.util.HttpUtil;
import com.example.admin.datasupport.util.Utility;

import java.io.IOException;
import java.net.ResponseCache;

public class AutoUpdateService extends Service {
    @Override
    public IBinder onBind(Intent intent){
        return null;
    }
    @Override
    public int onStartCommand(Intent intent,int flags ,int startId){
        updateWeather();
        updateBingPic();
        AlarmManager manager =(AlarmManager)getSystemService(ALARM_SERVICE);
        int anHour = 8*60*60*1000;//这是8小时的毫秒数
        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
        Intent  i = new Intent(this,AutoUpdateService.class);
        pendingIntent pi = PendingIntent.getService(this,0,i,0);
        manager.cancel(pi);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi);
        return super.onStartCommand(intent,flags,startId);
    }
    /**
     * 更新天气信息
     */
    private void updateWeather(){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String weatherString = prefs.getString("weather",null);
        if (weatherString != null){
            //有缓存时直接解析天气
            Weather weather = Utility.handleCityResponse(weatherString);
            String weatherId = weather.basic.weatherId;
            String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId +"&key=bc0418b57b2d4918819d3974ac1285d9";
            HttpUtil.sendOkHttpRequest(weatherUrl,new Handler.Callback(){
                @Override
                public void onReaponse(Call call,Response response)throws IOException{
                    String reaponseText = response.body().string();
                    Weather weather = Utility.handleWeatherReaponse(responseText);
                    if(weather != null && "ok".equals(weather.status)){
                        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit();
                        editor.putString("weather",reaponseText);
                        editor.apply();;
                    }
                }
                @Override
                        public void onFailure(Call call, IOException e){
                    e.printStackTrace();
                }
            });
        }
    }
    /**
     * 更新必应每日一图
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void updateBingPic(){
        String requestBingPic = "Http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBingPic, new Call.Callback(){
           @Override
            public void onResponse(Call call, Response response)throws IOException{
               String bingPic = response.body().string();
               SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit();
               editor.putString("bing_pic",bingPic);
               editor.apply();
           }
           @Override
            public void onFailure(Call call,IOException e){
               e.printStackTrace();
           }
        });
    }
}
